const qiniu =require("qiniu")

class QiniuClass {
   constructor(){
     //上传凭证
     this.accessKey = 'KU-wUinCdG0Q2qmAO5AEBMOf4_uOyghEqGc3wFUR';
     this.secretKey = 'ZQaiYVqkjVbXc33ZE7KVlSaQznyfiQ4KNvGKdynf';
     this.mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);

     //配置
     this.config = new qiniu.conf.Config();
     // 空间对应的机房(华东)
     this.config.zone = qiniu.zone.Zone_z0;

     this.formUploader = new qiniu.form_up.FormUploader(this.config);
     this.putExtra = new qiniu.form_up.PutExtra();

     this.bucketManager = new qiniu.rs.BucketManager(this.mac, this.config);

     //外链域名
     this.publicBucketDomain = 'http://q8bf7zqd4.bkt.clouddn.com';
   }
   //上传文件
   uploadFile(key,localFile){
     this.key = key;//文件名
     this.localFile = localFile;//文件路径

     //生成凭证
     let options = {
       scope: "cloud-doc1"+ ":" + key,//空间管理名称和文件名（覆盖）
     };
     const putPolicy = new qiniu.rs.PutPolicy(options);
     const uploadToken=putPolicy.uploadToken(this.mac);

     this.formUploader.putFile(uploadToken, key, localFile, this.putExtra, function(respErr,
       respBody, respInfo) {
       if (respErr) {
         throw respErr;
       }
       if (respInfo.statusCode == 200) {
         console.log(respBody);
       } else {
         console.log(respInfo.statusCode);
         console.log(respBody);
       }
     });
   }
   //删除文件
   deleteFile(key){
      var bucket = "cloud-doc1";//空间名
      var key = key;
      this.bucketManager.delete(bucket, key, function(err, respBody, respInfo) {
        if (err) {
          console.log(err);
          //throw err;
        } else {
          console.log(respInfo.statusCode);
          console.log(respBody);
        }
      });
   }
   //获取文件下载url
   getFileUrl(key){
      // 公开空间访问链接
      var publicDownloadUrl = this.bucketManager.publicDownloadUrl(this.publicBucketDomain, key);
      console.log(publicDownloadUrl);
   }
}

module.exports = {
  QiniuClass,
}
